package com.sneakxy.mybase4j.base.controller;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.sneakxy.mybase4j.shiro.bean.ShiroAccount;
import com.sneakxy.mybase4j.shiro.bean.ShiroSetting;
import com.sneakxy.mybase4j.util.Response;
import com.sneakxy.mybase4j.util.StringEscapeEditor;

/**
 * @author 潜行的青衣
 * @see
 */
public abstract class BaseController {

	protected final Logger log = LogManager.getLogger(this.getClass());
	
	@Resource
	protected ShiroSetting shiroSetting;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new StringEscapeEditor());
	}
	
	public Map<String, FieldError> getFieldErrors(BindingResult result) {
		Map<String, FieldError> errors = new LinkedHashMap<String, FieldError>();
		Iterator<FieldError> it = result.getFieldErrors().iterator();
		FieldError error = null;
		while(it.hasNext()) {
			error = it.next();
			errors.put(error.getField(), error);
		}
		return errors;
	}
	
	public Response getFieldErrorsResponse(BindingResult result) {
		return new Response(false, getFieldErrors(result));
	}
	
	public boolean hasRole(String roleIdentifier) {
		return SecurityUtils.getSubject().hasRole(roleIdentifier);
	}
	
	public boolean isPermitted(String permission) {
		return SecurityUtils.getSubject().isPermitted(permission);
	}
	
	public ShiroAccount getLoginAccount() {
		return (ShiroAccount) SecurityUtils.getSubject().getPrincipal();
	}
	
}
